package com.fengjing.launcher.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.os.SystemProperties;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fengjing.launcher.R;
import com.haijing.highglass.HmdBrightness;
import com.haijing.highglass.HmdContrast;
import com.haijing.highglass.HmdCtrl;
import com.haijing.highglass.HmdSaturation;
import com.hg.library.os.System;
import com.hg.library.widget.HiToast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wangjianqiang on 2016/9/13.
 */
public class CITActivity extends Activity implements SensorEventListener {


    private final String[] USB_STORAGE_PATHS = new String[]{"/mnt/usb_storage_sda/", "/mnt/usb_storage_sdb/", "/mnt/usb_storage_sdc/", "/mnt/usb_storage_sdd/", "/mnt/usb_storage_sde/"
            , "/mnt/usb_storage_sdf/", "/mnt/usb_storage_sdg/", "/mnt/usb_storage_sdh/", "/mnt/usb_storage_sdi/", "/mnt/usb_storage_sdj/", "/mnt/usb_storage_sdk/"
            , "/mnt/usb_storage_sdl/", "/mnt/usb_storage_sdm/", "/mnt/usb_storage_sdn/", "/mnt/usb_storage_sdo/", "/mnt/usb_storage_sdp/"};

    private Button headset_ok_btn, headset_not_ok_btn, led_ok_btn, led_not_ok_btn, completed_btn, record_btn, bluetooth_rescan_btn, record_voice_btn, mic_ok_btn, mic_not_ok_btn;
    private ImageView wifi_img, bluetooth_img, sdcard_img, headset_img, usb_img, led_img, up_img, down_img, left_img,
            right_img, ok_img, home_im, back_img, vadd_img, vsub_img, menu_img, edid_img, mic_img, record_img, glass_img, distance_img;
    private TextView record_tv, num_tv, storage_tv, accelerometer_tv, geogry_tv, magic_tv;

    private WifiManager mWifiManager;
    private BluetoothAdapter mBluetoothAdater;

    private int T_CARD = 0, USB = 0, WIFI = 0, BLUETOOTH = 0, HEADSET = 2, LED = 2;
    private int UP = 0, DOWN = 0, LEFT = 0, RIGHT = 0, OK = 0, HOME = 0, BACK = 0, VADD = 0, VSUB = 0, MENU = 0, MIC = 0, RECORD_RESULT = 0, EDID = 0, GLASS = 0, DISTANCE = 0;

    private MediaPlayer myMediaPlayer;
    private AnimationSet wifiAnimationSet, bluetoothAnimationSet;
    private RotateAnimation wifiRotateAnimation, bluetoothRotateAnimation;

    private int wifiRepeatCount = 0, bluetoothRepeatCount = 0;//???????????

    private String TEST = "TEST";

    private Timer timer;

    private Myhandler myhandler;
    private MediaRecorder myRecorder;
    private boolean isRecording = false;
    private byte temDistance = -0x01;
    private SensorManager sm;

    private List<Integer> imageList;

    private ImageView test_image;
    private int imagePosition = 0;

    public interface OnFinishedTest {
        void onFinished();
    }

    private AudioManager audioManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_layout);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 5, 0);
        myhandler = new Myhandler();

        imageList = new ArrayList<>();
        imageList.add(R.drawable.white);
        imageList.add(R.drawable.black);
        imageList.add(R.drawable.blue);
        imageList.add(R.drawable.darkblue);

        imageList.add(R.drawable.green);
        imageList.add(R.drawable.pink);
        imageList.add(R.drawable.red);
        imageList.add(R.drawable.yellow);
        imageList.add(R.drawable.color);

        initAnimation();

        initView();

        initReceiver();

        initDevices();

        playMusic();

        startFlashLED();

        setSNum();

        getStorageNum();

        startTimer();
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        if (sm != null) {
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_FASTEST);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_FASTEST);
        }
        setHighBrightness();
    }

    private OnFinishedTest onFinishedTest;


    private void initView() {
        headset_ok_btn = (Button) findViewById(R.id.cit_test_headset_btn_ok);
        headset_not_ok_btn = (Button) findViewById(R.id.cit_test_headset_btn_not_ok);
        led_ok_btn = (Button) findViewById(R.id.cit_test_headset_led_ok);
        led_not_ok_btn = (Button) findViewById(R.id.cit_test_headset_led_not_ok);
        completed_btn = (Button) findViewById(R.id.test_completed_btn);
//        wifi_rescan_btn = (Button) cITView.findViewById(R.id.cit_test_wifi_rescan_btn);
        bluetooth_rescan_btn = (Button) findViewById(R.id.cit_test_bluetooth_rescan_btn);
        record_btn = (Button) findViewById(R.id.test_record_btn);
        record_voice_btn = (Button) findViewById(R.id.cit_test_record_voice_btn);
        mic_ok_btn = (Button) findViewById(R.id.cit_test_mic_ok_btn);
        mic_not_ok_btn = (Button) findViewById(R.id.cit_test_mic_not_ok_btn);
        initListener();

        wifi_img = (ImageView) findViewById(R.id.cit_test_wifi_img);
        bluetooth_img = (ImageView) findViewById(R.id.cit_test_bluetooth_img);
        sdcard_img = (ImageView) findViewById(R.id.cit_test_sd_img);
        headset_img = (ImageView) findViewById(R.id.cit_test_headset_img);
        usb_img = (ImageView) findViewById(R.id.cit_test_usb_img);
        up_img = (ImageView) findViewById(R.id.cit_test_up_img);
        led_img = (ImageView) findViewById(R.id.cit_test_led_img);
        down_img = (ImageView) findViewById(R.id.cit_test_down_img);
        left_img = (ImageView) findViewById(R.id.cit_test_left_img);
        right_img = (ImageView) findViewById(R.id.cit_test_right_img);
        ok_img = (ImageView) findViewById(R.id.cit_test_ok_img);
        home_im = (ImageView) findViewById(R.id.cit_test_home_img);
        back_img = (ImageView) findViewById(R.id.cit_test_back_img);
        vadd_img = (ImageView) findViewById(R.id.cit_test_vadd_img);
        vsub_img = (ImageView) findViewById(R.id.cit_test_vsub_img);
        menu_img = (ImageView) findViewById(R.id.cit_test_menu_img);
        record_tv = (TextView) findViewById(R.id.cit_test_record_tv);
        edid_img = (ImageView) findViewById(R.id.cit_test_edid_img);
        mic_img = (ImageView) findViewById(R.id.cit_test_mic_img);
        record_img = (ImageView) findViewById(R.id.cit_test_mic_record_img);
        glass_img = (ImageView) findViewById(R.id.cit_test_glass_img);
        distance_img = (ImageView) findViewById(R.id.cit_test_distance_img);

        accelerometer_tv = (TextView) findViewById(R.id.accelerometer_tv);
        geogry_tv = (TextView) findViewById(R.id.geogry_tv);
        magic_tv = (TextView) findViewById(R.id.magic_tv);

        num_tv = (TextView) findViewById(R.id.test_num_tv);
        storage_tv = (TextView) findViewById(R.id.storage_num_tv);
        //wifi bluetooth test
        wifi_img.startAnimation(wifiAnimationSet);

        bluetooth_img.setAnimation(bluetoothAnimationSet);
        test_image = (ImageView) findViewById(R.id.test_image);
    }

    void initAnimation() {
        wifiAnimationSet = new AnimationSet(true);
        bluetoothAnimationSet = new AnimationSet(true);

        wifiRotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        wifiRotateAnimation.setDuration(1000);
        wifiRotateAnimation.setRepeatCount(-1);
        wifiAnimationSet.addAnimation(wifiRotateAnimation);

        bluetoothRotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        bluetoothRotateAnimation.setDuration(1000);
        bluetoothRotateAnimation.setRepeatCount(-1);
        bluetoothAnimationSet.addAnimation(bluetoothRotateAnimation);
    }

    void initReceiver() {
//        myFilter = new IntentFilter();
//        myFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
//        myFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//        myFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
//        myFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
//        myFilter.addAction(BluetoothDevice.ACTION_FOUND);
//        myFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//        myReceiver = new MyBroadcastReceiver();
//        registerReceiver(myReceiver, myFilter);

        myReceiver = new MyBroadcastReceiver();
        myFilter = new IntentFilter();
        myFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        myFilter.addDataScheme("file");
        registerReceiver(myReceiver, myFilter);
    }

    void initDevices() {
//        wifiStartScan();
//        bluetoothStartScan();

        if (hasUsbStorage()) {
            usb_img.setImageResource(R.drawable.ok);
        }

        if (hasSDStorage()) {
            sdcard_img.setImageResource(R.drawable.ok);
        }
    }

    void playMusic() {
        myMediaPlayer = MediaPlayer.create(this, R.raw.jiangnan_style);
        myMediaPlayer.setLooping(true);
        try {
            myMediaPlayer.prepare();

        } catch (Exception e) {

        }
        myMediaPlayer.start();


    }


    void startFlashLED() {
        try {
            FileWriter writer = new FileWriter("/sys/kernel/debug/bq25890/led_mode", false);
            writer.write("test");
            writer.flush();

        } catch (Exception e) {
//            Log.e("fuckyou ass hole",e.getMessage()+"shit");
        }
        try {
            FileWriter lcd_writer = new FileWriter("/sys/class/display/HDMI/lock_enable", false);
            lcd_writer.write("0");
            lcd_writer.flush();
        } catch (Exception e) {
//           Log.e("fuck you",e.toString()+"ssss");
        }
    }

    void setSNum() {
        String serialNum = null;
        try {
            serialNum = SystemProperties.get("ro.boot.serialno");
            if (serialNum == null || serialNum.equals("")) {
                serialNum = getString(R.string.unkown_num);
            }
        } catch (Exception e) {
            serialNum = getString(R.string.unkown_num);
        }
        num_tv.setText(getString(R.string.s_num) + serialNum);
    }

    void getStorageNum() {
        long sum = getTotalSize(getInnerSDCardPath());
        String storage_sum = FormetFileSize(sum);
        storage_tv.setText(getString(R.string.storage_sum) + storage_sum);
    }

    void endFlashLED() {
        try {
            FileWriter writer = new FileWriter("/sys/kernel/debug/bq25890/led_mode", false);
            writer.write("normal");
            writer.flush();

        } catch (Exception e) {
//            Log.e("fuckyou ass hole",e.getMessage()+"shit");
        }
        try {
            FileWriter lcd_writer = new FileWriter("/sys/class/display/HDMI/lock_enable", false);
            lcd_writer.write("1");
            lcd_writer.flush();
        } catch (Exception e) {

        }
    }

    void initListener() {
//        wifi_rescan_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                wifiStartScan();
//            }
//        });
        bluetooth_rescan_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothStartScan();
            }
        });
        headset_ok_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headset_img.setImageResource(R.drawable.ok);
                HEADSET = 1;
            }
        });
        headset_not_ok_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headset_img.setImageResource(R.drawable.not_ok);
                HEADSET = 0;
            }
        });
        led_ok_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                led_img.setImageResource(R.drawable.ok);
                LED = 1;
            }
        });
        led_not_ok_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                led_img.setImageResource(R.drawable.not_ok);
                LED = 0;
            }
        });
        completed_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                completed_btn.setEnabled(false);
                setRecord();
                endFlashLED();
                Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
                intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
//                onFinishedTest.onFinished();
            }
        });
        record_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                record_tv.setText(getRecord());
            }
        });
        record_voice_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isRecording) {
                    File file;
                    try {
                        file = new File(getFilesDir(), "record.mp3");
                        if (file.exists()) {
                            file.delete();
                        }
                        myMediaPlayer.stop();
                        file.createNewFile();
                        myRecorder = new MediaRecorder();
                        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                        myRecorder.setOutputFile(file.getAbsolutePath());
                        myRecorder.prepare();
                        // 开始录音
                        myRecorder.start();
                        record_voice_btn.setText(R.string.stop_record);
                        isRecording = true;
                    } catch (Exception e) {
                        record_voice_btn.setText(R.string.start_record);
                        isRecording = false;
                    }
                } else {
                    isRecording = false;
                    record_voice_btn.setText(R.string.start_record);
                    myRecorder.stop();
                    myRecorder.release();
                    try {
                        File file = new File(getFilesDir(), "record.mp3");
                        if (file.exists()) {
                            myMediaPlayer.reset();
                            myMediaPlayer.setDataSource(file.getAbsolutePath());
                            myMediaPlayer.prepare();
                            myMediaPlayer.start();
                        } else {
                            HiToast.showMessage(CITActivity.this, "没有录音文件", Toast.LENGTH_SHORT);
                        }
                    } catch (Exception e) {

                    }
                }
            }
        });
        mic_ok_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                record_img.setImageResource(R.drawable.ok);
                RECORD_RESULT = 1;
            }
        });
        mic_not_ok_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                record_img.setImageResource(R.drawable.not_ok);
                RECORD_RESULT = 0;
            }
        });
    }


    void wifiStartScan() {
//        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        if (!mWifiManager.isWifiEnabled()) {
//            mWifiManager.setWifiEnabled(true);
//        } else {
//            mWifiManager.startScan();
//        }
    }

    void bluetoothStartScan() {
        mBluetoothAdater = BluetoothAdapter.getDefaultAdapter();
        bluetooth_img.setImageResource(R.drawable.not_ok);
        bluetooth_img.startAnimation(bluetoothAnimationSet);
        if (!mBluetoothAdater.isEnabled()) {
            mBluetoothAdater.enable();
        } else {
            mBluetoothAdater.startDiscovery();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (test_image.getVisibility() == View.VISIBLE && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_DPAD_LEFT:
                        imagePosition = imagePosition == 0 ? 0 : imagePosition - 1;
                        if (imagePosition == 0) {
                            setHighBrightness();
                        }
                        test_image.setImageResource(imageList.get(imagePosition));
                        break;
                    case KeyEvent.KEYCODE_DPAD_RIGHT:
                        if (imagePosition == 8) {
                            test_image.setVisibility(View.GONE);
                        } else {
                            imagePosition = imagePosition + 1;
                            if (imagePosition == 1) {
                                setDefault();
                            }
                            test_image.setImageResource(imageList.get(imagePosition));
                        }
                        break;
                }
            }
            return true;
        }
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_DPAD_UP:
                up_img.setImageResource(R.drawable.ok);
                UP = 1;
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                down_img.setImageResource(R.drawable.ok);
                DOWN = 1;
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                left_img.setImageResource(R.drawable.ok);
                LEFT = 1;
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                right_img.setImageResource(R.drawable.ok);
                RIGHT = 1;
                break;
            case KeyEvent.KEYCODE_ENTER:
                ok_img.setImageResource(R.drawable.ok);
                OK = 1;
                break;
            case KeyEvent.KEYCODE_DPAD_CENTER:
                ok_img.setImageResource(R.drawable.ok);
                OK = 1;
                break;
            case KeyEvent.KEYCODE_HOME:
                home_im.setImageResource(R.drawable.ok);
                HOME = 1;
                return true;
            case KeyEvent.KEYCODE_BACK:
                back_img.setImageResource(R.drawable.ok);
                BACK = 1;
                return true;
            case KeyEvent.KEYCODE_MENU:
                menu_img.setImageResource(R.drawable.ok);
                MENU = 1;
                setDefault();
                break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                vadd_img.setImageResource(R.drawable.ok);
                VADD = 1;
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                vsub_img.setImageResource(R.drawable.ok);
                VSUB = 1;
                break;
            case KeyEvent.KEYCODE_MEDIA_RECORD:
                mic_img.setImageResource(R.drawable.ok);
                MIC = 1;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sm != null) {
            sm.unregisterListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
        myMediaPlayer.stop();
        myMediaPlayer.release();
        myMediaPlayer = null;
    }

    private IntentFilter myFilter;
    private MyBroadcastReceiver myReceiver;

    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                home_im.setImageResource(R.drawable.ok);
                HOME = 1;
            }
            if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {

//                if (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
//                    mWifiManager.startScan();
//                }

            }
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {

                List configs = mWifiManager.getScanResults();
                if (configs.size() > 0) {
                    wifi_img.clearAnimation();
                    wifi_img.setImageResource(R.drawable.ok);
                    WIFI = 1;
                } else {
                    if (wifiRepeatCount > 2) {
                        wifi_img.clearAnimation();
                    } else {
//                        ++wifiRepeatCount;
//                        mWifiManager.startScan();
                    }
                }

            }
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

                if (mBluetoothAdater.isEnabled()) {
                    mBluetoothAdater.startDiscovery();
                }
            }
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                bluetooth_img.clearAnimation();
                bluetooth_img.setImageResource(R.drawable.ok);
                mBluetoothAdater.cancelDiscovery();
                BLUETOOTH = 1;
            }

            if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                if (BLUETOOTH != 1) {
                    if (bluetoothRepeatCount > 2) {
                        bluetooth_img.clearAnimation();
                    } else {
                        ++bluetoothRepeatCount;
                        mBluetoothAdater.startDiscovery();
                    }
                }
            }

            if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
                String path = intent.getData().getPath();
                if (path.contains("usb_storage")) {
                    if (hasUsbStorage()) {
                        usb_img.setImageResource(R.drawable.ok);
                    }
                }
                if (hasSDStorage()) {
                    sdcard_img.setImageResource(R.drawable.ok);
                }
            }
        }
    }

    private boolean hasUsbStorage() {
        boolean has = false;
        String path = getAvailablePath(USB_STORAGE_PATHS);
        byte[] buffer = new String(TEST).getBytes();
        if (path != null) {
            try {
                File file = new File(path, "test.txt");
                if (file.exists()) {
                    file.delete();
                }
                OutputStream outputStream = new FileOutputStream(file);
                outputStream.write(buffer);
                outputStream.flush();
                outputStream.close();

                File infile = new File(path, "test.txt");
                if (!file.exists()) {
                    return false;
                }
                InputStream in = new FileInputStream(infile);
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = reader.readLine();
                in.close();
                infile.delete();
                if (line.equals(TEST)) {
                    USB = 1;
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {

            }

        }
        return has;
    }


    boolean hasSDStorage() {
        try {
            File exfile = new File("/mnt/sdcard1");
            File[] files = exfile.listFiles();
            if (files != null) {
                String path = "/mnt/sdcard1";
                byte[] buffer = new String(TEST).getBytes();
                File file = new File(path, "test.txt");
                if (file.exists()) {
                    file.delete();
                }
                OutputStream outputStream = new FileOutputStream(file);
                outputStream.write(buffer);
                outputStream.flush();
                outputStream.close();

                File infile = new File(path, "test.txt");
                if (!file.exists()) {
                    return false;
                }
                InputStream in = new FileInputStream(infile);
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = reader.readLine();
                in.close();
                infile.delete();
                if (line.equals(TEST)) {
                    T_CARD = 1;
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
        }

        return false;

    }

    private String getRecord() {
        String res = "";
        try {
            FileInputStream fin = new FileInputStream(getFilesDir() + "/test_record.txt");
            int length = fin.available();

            byte[] buffer = new byte[length];

            fin.read(buffer);

            res = new String(buffer, "UTF-8");

            fin.close();

        } catch (Exception e) {

//            Log.e("fuck you ass", e.getMessage() + "fuck");

        }
        return res;
    }

    private void setRecord() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("\n");
        if (T_CARD != 1) {
            stringBuilder.append(getString(R.string.sdcard_fail) + "    ");
        }
        if (USB != 1) {
            stringBuilder.append(getString(R.string.usb_fail) + "    ");
        }
        if (WIFI != 1) {
            stringBuilder.append(getString(R.string.wifi_fail) + "    ");
        }
        if (BLUETOOTH != 1) {
            stringBuilder.append(getString(R.string.buletooth_fail) + "    ");
        }
        if (HEADSET == 0) {
            stringBuilder.append(getString(R.string.headset_fail) + "    ");
        } else if (HEADSET == 2) {
            stringBuilder.append(getString(R.string.headset_untested) + "    ");
        }
        if (LED == 0) {
            stringBuilder.append(getString(R.string.led_fail) + "    ");
        } else if (LED == 2) {
            stringBuilder.append(getString(R.string.led_untested) + "    ");
        }
        if (UP != 1) {
            stringBuilder.append(getString(R.string.up_fail) + "    ");
        }
        if (DOWN != 1) {
            stringBuilder.append(getString(R.string.down_fail) + "    ");
        }
        if (LEFT != 1) {
            stringBuilder.append(getString(R.string.left_fail) + "    ");
        }
        if (RIGHT != 1) {
            stringBuilder.append(getString(R.string.right_fail) + "    ");
        }
        if (OK != 1) {
            stringBuilder.append(getString(R.string.ok_fail) + "    ");
        }
        if (HOME != 1) {
            stringBuilder.append(getString(R.string.home_fail) + "    ");
        }
        if (BACK != 1) {
            stringBuilder.append(getString(R.string.back_fail) + "    ");
        }
        if (VADD != 1) {
            stringBuilder.append(getString(R.string.vadd_fail) + "    ");
        }
        if (VSUB != 1) {
            stringBuilder.append(getString(R.string.vsub_fail) + "    ");
        }
        if (MENU != 1) {
            stringBuilder.append(getString(R.string.menu_fail) + "    ");
        }
        if (MIC != 1) {
            stringBuilder.append(getString(R.string.mic_fail) + "    ");
        }
        if (RECORD_RESULT != 1) {
            stringBuilder.append(getString(R.string.mic_record_fail) + "    ");
        }
        if (EDID != 1) {
            stringBuilder.append(getString(R.string.edid_fail) + "    ");
        }
        if (GLASS != 1) {
            stringBuilder.append(getString(R.string.glass_fail) + "    ");
        }
        if (DISTANCE != 1) {
            stringBuilder.append(getString(R.string.distance_fail) + "    ");
        }
//        Log.e("fuck you ass" + getFilesDir(), stringBuilder.toString() + "fuck");
        try {

            File file = new File(getFilesDir(), "test_record.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter writer = new FileWriter(getFilesDir() + "/test_record.txt", true);
            writer.write(stringBuilder.toString());
            writer.close();
        } catch (IOException e) {

        }

    }

    public void setOnFinishedTest(OnFinishedTest onFinishedTest) {
        this.onFinishedTest = onFinishedTest;
    }

    private String getAvailablePath(String[] paramStrings) {
        String path = null;
        for (String paramString : paramStrings) {
            File root = new File(paramString);
            File[] files = root.listFiles();
            if (files != null && files.length > 0) {
                path = files[0].getPath();
                return path;
            }
        }
        return path;
    }

    private void startTimer() {
        timer = new Timer();
        timer.schedule(new MytimerTask(), 1000, 1000);
    }

    private class MytimerTask extends TimerTask {
        @Override
        public void run() {
            try {
                File file = new File("/sys/devices/virtual/display/HDMI/edid_state");
                InputStream in = new FileInputStream(file);
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line = reader.readLine();
                if (line.contains("-1")) {
                    myhandler.sendEmptyMessage(2);
                } else if (line.contains("1")) {
                    myhandler.sendEmptyMessage(1);
                } else if (line.contains("0")) {
                    myhandler.sendEmptyMessage(0);
                }
            } catch (Exception e) {
            }
            HmdBrightness hmdBrightness = HmdCtrl.getBrightness();
            if (hmdBrightness != null) {
                myhandler.sendEmptyMessage(4);
            }
            byte temstate = HmdCtrl.getVideoState();
            if (temstate != HmdCtrl.HMD_CTRL_PARAM_DISP_VIDEO_STATE_ERROR) {
                if (temDistance != -0x01 && temstate != temDistance) {
                    myhandler.sendEmptyMessage(5);
                }
                temDistance = temstate;
            }
        }
    }

    private class Myhandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    edid_img.setImageResource(R.drawable.question);
                    break;
                case 1:
                    edid_img.setImageResource(R.drawable.ok);
                    EDID = 1;
                    break;
                case 2:
                    edid_img.setImageResource(R.drawable.not_ok);
                    break;
                case 4:
                    glass_img.setImageResource(R.drawable.ok);
                    GLASS = 1;
                    break;
                case 5:
                    distance_img.setImageResource(R.drawable.ok);
                    DISTANCE = 1;
                    break;
            }
        }
    }

    public static long getTotalSize(String paramString) {
        StatFs localStatFs = new StatFs(paramString);
        localStatFs.restat(paramString);
        try {
            long l = localStatFs.getBlockCountLong();
            long i = localStatFs.getBlockSizeLong();
            return l * i;
        } catch (Exception localException) {
        }
        return 0L;
    }

    public String FormetFileSize(long paramLong) {
        DecimalFormat localDecimalFormat = new DecimalFormat("#.0");
        if (paramLong < 1024L) {
            return localDecimalFormat.format(paramLong) + "B";
        }
        if (paramLong < 1048576L) {
            return localDecimalFormat.format(paramLong / 1024.0D) + "K";
        }
        if (paramLong < 1073741824L) {
            return localDecimalFormat.format(paramLong / 1048576.0D) + "M";
        }
        return localDecimalFormat.format(paramLong / 1.073741824E9D) + "G";
    }

    public String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        try {
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                float[] values = event.values;
                accelerometer_tv.setText("加速度传感器：x = " + values[0] + " y = " + values[1] + " z = " + values[2]);
            }
        } catch (Exception e) {

        }
        try {
            if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                float[] values = event.values;
                magic_tv.setText("磁场传感器：x = " + values[0] + " y = " + values[1] + " z = " + values[2]);
            }
        } catch (Exception e) {

        }
        try {
            if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
                float[] values = event.values;
                geogry_tv.setText("陀螺仪传感器：x = " + values[0] + " y = " + values[1] + " z = " + values[2]);
            }
        } catch (Exception e) {

        }
    }

    private void setDefault() {
        int device = System.Device.getMonitorModel();
        HmdBrightness bightness;
        if (device == System.Device.MONITOR_DH1 || isOldMonitor()) {
            bightness = HmdCtrl.getBrightness();
        } else {
            bightness = HmdCtrl.getBrightnessAbs();
        }
        if (bightness != null) {
            if (device == System.Device.MONITOR_DH1 || isOldMonitor()) {
                bightness.w = 48;
                HmdCtrl.setBrightness(bightness);
            } else {
                bightness.w = 110;
                HmdCtrl.setBrightnessAbs(bightness);
            }
        }
    }

    private boolean isOldMonitor() {
        try {
            String version = HmdCtrl.getVersion();
            String[] split = version.split("\\.");

            if (split.length >= 2 && Integer.valueOf(split[0]) == 1 && Integer.valueOf(split[1]) < 8) {
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    private void setHighBrightness() {
        int device = System.Device.getMonitorModel();
        HmdBrightness bightness;
        if (device == System.Device.MONITOR_DH1 || isOldMonitor()) {
            bightness = HmdCtrl.getBrightness();
        } else {
            bightness = HmdCtrl.getBrightnessAbs();
        }
        if (bightness != null) {
            if (device == System.Device.MONITOR_DH1 || isOldMonitor()) {
                bightness.w = 100;
                bightness = HmdCtrl.setBrightness(bightness);
            } else {
                bightness.w = 138;
                bightness = HmdCtrl.setBrightnessAbs(bightness);
            }
        }
        HmdCtrl.setContrast(new HmdContrast(50, 50, 50, 50));
        HmdCtrl.setSaturation(new HmdSaturation(42, 42, 42, 42));
    }
}
